"""
13_chatbot.py - Production Chatbot
====================================
Chapter 15: From simple chatbot to full conversational AI.

Run: python src/13_chatbot.py
"""
from typing import TypedDict, Annotated
from operator import add
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

class ChatbotState(TypedDict):
    messages: Annotated[list, add]
    intent: str
    response: str

def detect_intent(state: ChatbotState) -> dict:
    msg = str(state["messages"][-1]).lower()
    if any(w in msg for w in ["help", "support", "issue"]):
        return {"intent": "support"}
    elif any(w in msg for w in ["buy", "price", "order"]):
        return {"intent": "sales"}
    elif any(w in msg for w in ["bye", "thanks"]):
        return {"intent": "farewell"}
    return {"intent": "general"}

def route_intent(state: ChatbotState) -> str:
    return {"support": "support_bot", "sales": "sales_bot", "farewell": "farewell_bot"}.get(state["intent"], "general_bot")

def support_bot(state: ChatbotState) -> dict:
    return {"messages": ["[Support] How can I help resolve your issue?"], "response": "Support engaged"}
def sales_bot(state: ChatbotState) -> dict:
    return {"messages": ["[Sales] Let me find the right product for you!"], "response": "Sales engaged"}
def farewell_bot(state: ChatbotState) -> dict:
    return {"messages": ["[Bot] Goodbye! Have a great day!"], "response": "Farewell"}
def general_bot(state: ChatbotState) -> dict:
    return {"messages": ["[Bot] How can I assist you today?"], "response": "General response"}

graph = StateGraph(ChatbotState)
graph.add_node("detect", detect_intent)
for n, f in [("support_bot", support_bot), ("sales_bot", sales_bot), ("farewell_bot", farewell_bot), ("general_bot", general_bot)]:
    graph.add_node(n, f)
graph.add_edge(START, "detect")
graph.add_conditional_edges("detect", route_intent)
for n in ["support_bot", "sales_bot", "farewell_bot", "general_bot"]:
    graph.add_edge(n, END)

chatbot = graph.compile(checkpointer=MemorySaver())

if __name__ == "__main__":
    print("=" * 60)
    print("13: Production Chatbot")
    print("=" * 60)
    config = {"configurable": {"thread_id": "user_1"}}
    for msg in ["Hello!", "I need help with my order", "Thanks, bye!"]:
        result = chatbot.invoke({"messages": [msg]}, config=config)
        print(f"\n  User: {msg}")
        print(f"  Intent: {result['intent']}")
        print(f"  Bot: {result['messages'][-1]}")
    print(f"\n{'=' * 60}\n✅ Chatbot complete!")
